<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col
        :span="24"
        :xs="24"
      >
        <!-- 数据筛选表单 -->
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="100px"
        >
          <!-- 数据筛选表单组件 -->
          <el-form-item
            label="图片标题"
            prop="title"
          >
            <el-input
              v-model="queryParams.title"
              placehold
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item
            label="文件名"
            prop="fileName"
          >
            <el-input
              v-model="queryParams.fileName"
              placehold
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <!-- 数据筛选操作按钮 -->
          <el-form-item>
            <el-button
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
            >重置</el-button>

          </el-form-item>
          <el-form-item label="调整列数">
            <template>
              <el-input-number
                v-model="col"
                :min="3"
                :max="8"
                @change="handleChange"
              />
            </template>
          </el-form-item>

          <el-form-item style="margin-left: 30px;">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >上传图片</el-button>
          </el-form-item>
        </el-form>

        <!-- 上传图片表单 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="600px"
          append-to-body
        >
          <el-form
            ref="form1"
            :model="form1"
            :rules="rules1"
            width="100%"
            label-width="100px"
          >
            <el-form-item
              label="产品"
              prop="orderItems"
            >
              <el-select
                v-model="form1.productId"
                placeholder="请选择"
              >
                <el-option
                  v-for="productItem in ProductOptions"
                  :key="productItem.productId"
                  :label="productItem.productName"
                  :value="productItem.productId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="图片标题"
              prop="title"
            >
              <el-input
                v-model="form1.title"
                placeholder="选择产品后自动填充，可修改"
              />
            </el-form-item>
            <el-form-item>
              <el-upload
                :action="uploadApi"
                list-type="picture-card"
                :auto-upload="false"
                ref="upload"
                :limit="1"
                accept="image/*"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
              >
                <i
                  slot="default"
                  class="el-icon-plus"
                />
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="handleUploadFiles"
              >确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!-- 查看图片详情 -->
        <el-dialog :visible.sync="dialogVisible">
          <img
            width="100%"
            :src="dialogImageUrl"
            alt="无法显示，请重试"
          >
        </el-dialog>
        <el-dialog :visible.sync="viewImageVisible">
          <img
            width="100%"
            :src="viewImageUrl"
            alt="无法显示，请重试"
          >
        </el-dialog>

        <!-- 图片展示 -->
        <div class="waterfall">
          <image-water-fall
            ref="ImageWaterFall"
            :data="imageList"
            :col="col"
            @delete-image="deleteImage"
            @view-image="viewImage"
          />
          <!-- 数据分页加载 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 30]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  /** 导入axios Api */
  import { uploadOss, listOssByPage, getOss, addOss, updateOss, deleteOss } from '@/api/system/oss'
  import ImageWaterFall from '@/components/ImageWaterFall'
  import { listAllP } from '@/api/pos/product'
  import { compressImage } from './compress'
  export default {
    name: 'Oss',
    components: { ImageWaterFall },
    data() {
      return {
        // 遮罩层
        loading: false,
        // 总条数
        total: 0,
        // 当前页
        pageNum: 0,
        // 每页数据量
        pageSize: 0,
        // Oss表格数据，冒似没用了
        ossList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 数据查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          fileName: null
        },
        // 下拉框选项数据
        ProductOptions: [],
        // 上传图片数据
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        uploadApi: process.env.VUE_APP_BASE_API + '/sysOss/upload',
        fileVisible: false,
        // 图片预览
        viewImageUrl: '',
        viewImageVisible: false,
        //
        form1: {},
        // 展示图片数据
        col: 5,
        imageList: [],
        rules1: {
          title: [
            { required: true, message: '请输入图片标题', trigger: 'blur' }
          ],
        }
      }
    },
    created() {
      // this.getList()
    },
    watch: {
      'form1.productId'(newProductId) {
        const selectedProduct = this.ProductOptions.find(
          product => product.productId === newProductId
        );
        if (selectedProduct) {
          this.form1.title = selectedProduct.productName;
        }
      }
    },
    mounted() {
      this.getList();
      listAllP().then(response => {
        this.ProductOptions = response.data;
        console.log("成功获取响应数据：", response);
      }).catch(error => {
      });
    },
    methods: {
      /** 查询Oss数据列表 */
      getList() {
        this.loading = true
        listOssByPage(this.queryParams).then((response) => {
          console.log('阿里数据库是事实上事实上', response)
          this.imageList = response.data.list
          // this.ossList = response.data.list
          this.total = response.data.total
          this.loading = false
        })
      },
      /** 处理分页 */
      handleSizeChange(val) {
        this.queryParams.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.queryParams.pageNum = val
        this.getList()
      },

      /** 数据编辑对话框取消按钮 */
      cancel() {
        this.open = false
        this.resetForm1()
      },

      /** 重置分页 */
      resetQueryParams() {
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 10
      },

      /** 数据筛选搜索按钮 */
      handleQuery() {
        this.resetQueryParams()
        this.getList()
        this.$message.success('查询成功')
      },

      /** 数据筛选重置按钮 */
      resetQuery() {
        this.$refs.queryForm.resetFields()
        this.getList()
      },
      deleteImage(ossId) {
        console.log('删除图片', ossId)
        deleteOss(ossId).then(response => {
          console.log('删除结果', response)
          this.getList()
          this.$message.success('删除成功')
        })
      },
      /** 表单初始化 */
      resetForm1() {
        // 可进行数据初始化工作
        this.form1 = {
          productId: null,
          title: null,
        }
      },
      /** 处理添加图片按钮 */
      handleAdd() {
        // 清空上传队列
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
        this.resetForm1()
        this.fileVisible = true
        this.open = true
        this.title = '上传图片'
      },

      /** 手动上传图片 */
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleUploadFiles() {
        // console.log('上传图片',file)
        // this.$refs.upload.submit()
        this.upload();
      },
      upload() {
        // 获取上传组件实例
        const uploadInstance = this.$refs.upload;
        console.log('uploadInstance', uploadInstance);
        this.$nextTick(() => {
          // 获取文件列表
          const fileList = uploadInstance.uploadFiles;
          console.log('fileList', fileList);
          // 如果有文件
          if (fileList.length > 0) {
            // 获取第一个文件
            const file = fileList[0];
            console.log('file', file);
            console.log('file.size', file.size);
            //压缩图片
            if (file.size > 400 * 1024) {
              compressImage(file.raw)
                .then((compressedBlob) => {
                  // 处理压缩后的文件
                  console.log('compressedBlob', compressedBlob);
                  // 执行上传操作
                  this.uploadFile(compressedBlob);
                })
                .catch((error) => {
                  console.error('压缩失败', error);
                });
            } else {
              this.uploadFile(file.raw);
            }
          } else {
            // 没有文件，可以进行提示或其他操作
            console.log('没有选择文件');
          }
        });
      },
      uploadFile(raw) {
        uploadOss(raw, this.form1.productId, this.form1.title)
          .then(response => {
            // 上传成功，可以进行处理
            console.log('上传成功', response);
            this.$message.success('上传成功')
            this.open = false
            this.getList()
          })
          .catch(error => {
            // 上传失败，可以进行处理
            console.error('上传失败', error);
          });
      },
      /** 修改每页列数 */
      handleChange(value) {
        this.col = value
      },
      viewImage(ossId) {
        console.log('查看图片', ossId)
        this.viewImageUrl = this.imageList.find(item => item.ossId === ossId).fileUrl
        this.viewImageVisible = true
      }
    }
  }
</script>